package com.student.Activitys.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.isseiaoki.simplecropview.callback.LoadCallback;
import com.student.Activitys.R;
import com.student.Activitys.activity.base.BaseActivity;
import com.student.Activitys.bean.UserBean;
import com.student.Activitys.bean.UserUpdateIcon;
import com.student.Activitys.http.UploadUtil;
import com.student.Activitys.http.manager.MyManager;
import com.student.Activitys.other.HttpConstant;
import com.student.Activitys.utils.Constant;
import com.student.Activitys.utils.ImageUtils;
import com.student.Activitys.utils.ToastUtils;
import com.student.Activitys.view.MyCutSimpleCropView;

import org.simple.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * 项目名称：
 * 类描述：自定义裁剪页面
 * 创建人：张飞祥
 * 创建时间：2016/11/8 0008 下午 1:44
 * 修改人：张飞祥
 * 修改时间：2016/11/8 0008 下午 1:44
 * 修改备注：
 */
public class SimpleCropActivity extends BaseActivity {

    @Bind(R.id.iv_return)
    ImageView ivReturn;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.iv_save)
    ImageView ivSave;
    @Bind(R.id.cv_simple)
    MyCutSimpleCropView cvSimple;
    @Bind(R.id.iv_simple_default)
    ImageView ivSimpleDefault;
    @Bind(R.id.tv_simple_circular)
    TextView tvSimpleCircular;
    @Bind(R.id.tv_simple_arbitrarily)
    TextView tvSimpleArbitrarily;
    @Bind(R.id.tv_simple_3_4)
    TextView tvSimple34;
    @Bind(R.id.tv_simple_1_1)
    TextView tvSimple11;
    @Bind(R.id.tv_simple_4_3)
    TextView tvSimple43;
    @Bind(R.id.ib_simple_picture)
    ImageButton ibSimplePicture;
    @Bind(R.id.ib_simple_left)
    ImageButton ibSimpleLeft;
    @Bind(R.id.ib_simple_right)
    ImageButton ibSimpleRight;
    @Bind(R.id.ib_simple_level)
    ImageButton ibSimpleLevel;
    @Bind(R.id.ib_simple_vertical)
    ImageButton ibSimpleVertical;

    //初始化不可点击 按钮列表
    private List<ImageButton> ibList;
    //初始化网络请求
    public MyManager mApiManager;
    //获取学号
    public String xh;
    //获取当前用户身份
    public String identity;
    //头像上传 异步线程
    private Handler handler;
    //文件流 url
    private String fileUrl;
    //获取 上个页面传递过来的 头像地址 值
    private String initMyIcon;
    //加载进度 dialog
    protected MaterialDialog userUpIconDialog;
    //当前用户实体
    protected UserBean user;

    @Override
    protected void initUI() {
        //设置状态栏样式
        setContentView(R.layout.act_simple_crop);
        //网络请求 常驻方法
        mApiManager = mApiManager.getMyApiManager(SimpleCropActivity.this, SimpleCropActivity.this.getTaskId());
        //初始化裁剪
        cvSimple.setCropMode(MyCutSimpleCropView.CropMode.FREE);
        //标题
        tvTitle.setText("裁剪");
        //返回键
        ivReturn.setVisibility(View.VISIBLE);
        //保存按钮
        ivReturn.setImageResource(R.drawable.ic_close);
        //获取学号
        xh = mACache.getAsString(Constant.USER_XH);
        //获取当前用户身份
        identity = mACache.getAsString(Constant.USER_IDENTITY);
        /**
         * 获取当前内存中所保存的数据用户实体对象
         */
        Gson gson = new Gson();
        user =  gson.fromJson(mACache.getAsJSONObject(Constant.USER)+"", UserBean.class);

        //获取 传递过来的 头像地址
        Bundle bundle = this.getIntent().getExtras();    // 获取传递过来的封了数据的Bundle
        initMyIcon = bundle.getString(Constant.USER_ICON);
    }

    @Override
    protected void initData() {
        ibList = new ArrayList<>();
        ibList.add(ibSimpleLeft);
        ibList.add(ibSimpleRight);
        ibList.add(ibSimpleLevel);
        ibList.add(ibSimpleVertical);
        for (int i = 0; i < ibList.size(); i++) {
            ibList.get(i).setClickable(false);
        }

        //获取本地保存的当前头像 icon 添加带裁剪页面
        if (initMyIcon != null && !initMyIcon.equals("")) {
            /**
             *  1.添加 图片地址到裁剪 控件上
             *  2.新建线程加载图片信息，发送到消息队列中
             */
            new Thread(initMyIconRunnable).start();
        }
    }
    //添加用户图片到控件上
    private Handler initMyIconhandle = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 0){
                /***
                 *
                 * 1.显示裁剪控件、保存按钮，隐藏掉默认提示视图页面
                 * 2.循环将按钮变为可点击状态
                 */
                cvSimple.setVisibility(View.VISIBLE);
                ivSave.setVisibility(View.VISIBLE);
                ivSimpleDefault.setVisibility(View.GONE);
                for (int i = 0; i < ibList.size(); i++) {
                    ibList.get(i).setClickable(true);
                }
                //设置裁剪图片
                cvSimple.setImageBitmap((Bitmap) msg.obj);
            }
        };
    };
    /**
     * 头像上传网络操作相关的子线程
     */
    Runnable initMyIconRunnable = new Runnable() {
        @Override
        public void run() {
            Message msg = new Message();
            msg.what = 0;
            msg.obj = ImageUtils.getHttpBitmap(initMyIcon);
            initMyIconhandle.sendMessage(msg);
        }
    };
    @Override
    protected void getNotData() {

    }

    @OnClick({R.id.iv_return, R.id.iv_save, R.id.tv_simple_circular,
            R.id.tv_simple_arbitrarily, R.id.tv_simple_3_4, R.id.tv_simple_1_1, R.id.tv_simple_4_3,
            R.id.ib_simple_picture, R.id.ib_simple_left, R.id.ib_simple_right, R.id.ib_simple_level,
            R.id.ib_simple_vertical})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.iv_return:            //退出
                finish();
                break;
            case R.id.iv_save:              //保存
                Bitmap croppedBitmap = cvSimple.getCroppedBitmap();
                if (croppedBitmap!=null){
                    //将bitmap转换成Uri
                    Uri uri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), croppedBitmap, null, null));
                    fileUrl = ImageUtils.uri2File(uri,SimpleCropActivity.this).toString();
                    //弹出 dialog
                    initShowUserUpIconDialog("正在上传头像，请稍后...",SimpleCropActivity.this);
                    //网络上传头像
                    uploadeDo(uri);
                }else{
                    new MaterialDialog.Builder(SimpleCropActivity.this)
                            .title("错误")
                            .content("裁剪图片时出错，可能是图片已损坏或不是有效的图片文件，请重新选择进行上传！")
                            .negativeText("取消")
                            .positiveText("重新选择")
                            .onNegative(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(MaterialDialog dialog, DialogAction which) {
                                    dialog.dismiss();
                                }
                            })
                            .onPositive(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(MaterialDialog dialog, DialogAction which) {
                                    selectPicture();
                                    dialog.dismiss();
                                }
                            }).show();
                }
                break;
            case R.id.ib_simple_picture:      //选择图片
                selectPicture();
                break;
            case R.id.tv_simple_circular:     //圆形裁剪
                cvSimple.setCropMode(MyCutSimpleCropView.CropMode.CIRCLE_SQUARE);
                break;
            case R.id.tv_simple_arbitrarily:  //任意比例裁剪
                cvSimple.setCropMode(MyCutSimpleCropView.CropMode.FREE);
                break;
            case R.id.tv_simple_3_4:          //3:4裁剪
                cvSimple.setCropMode(MyCutSimpleCropView.CropMode.RATIO_3_4);
                break;
            case R.id.tv_simple_1_1:          //1:1裁剪
                cvSimple.setCropMode(MyCutSimpleCropView.CropMode.SQUARE);
                break;
            case R.id.tv_simple_4_3:          //4:3裁剪
                cvSimple.setCropMode(MyCutSimpleCropView.CropMode.RATIO_4_3);
                break;
            case R.id.ib_simple_left:         //向左翻转
                cvSimple.rotateImage(MyCutSimpleCropView.RotateDegrees.ROTATE_M90D);
                break;
            case R.id.ib_simple_right:        //向右翻转
                cvSimple.rotateImage(MyCutSimpleCropView.RotateDegrees.ROTATE_90D);
                break;
            case R.id.ib_simple_level:        //水平翻转
                cvSimple.getFlipBmp(Constant.LEVEL_FLIP);
                break;
            case R.id.ib_simple_vertical:     //垂直翻转
                cvSimple.getFlipBmp(Constant.VERTICAL_FLIP);
                break;
        }
    }

    /**
     * 开始上传 用户头像
     */
    private void uploadeDo(final Uri uri){
       // 开启一个子线程，进行网络操作，等待有返回结果，使用handler通知UI
       new Thread(networkTask).start();
        /**
         * 接收 上传成功的文件 返回信息
         *
         * if 返回结果 等于 0，则显示上传成功，并保存数据
         * else 弹出提示信息
         */
       handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                //销毁操作
                userUpIconDialog.dismiss();
                //接收传递过来的数据
                Bundle data = msg.getData();
                /**
                 * 创建 Gson 解析储存的用户数据 反填 界面数据
                 */
                Gson gson = new Gson();
                UserUpdateIcon userUpdateIcon = gson.fromJson(data.getString("value"), UserUpdateIcon.class);
                if (userUpdateIcon.getState().equals("1")){
                    ToastUtils.showShort(SimpleCropActivity.this,"上传成功");
                    //上传成功后的头像 保存当前用户实体上
                    user.setImg_url(userUpdateIcon.getUrl());
                    mACache.put(Constant.USER, new Gson().toJson(user));
                    //刷新我的页面头像
                    EventBus.getDefault().post(uri.toString(), Constant.SIMPLE_USER_ICON);
                    finish();
                }else{
                   ToastUtils.showShort(SimpleCropActivity.this,userUpdateIcon.getMsg());
                }
            }
        };
    }

    /**
     * 头像上传网络操作相关的子线程
     */
    Runnable networkTask = new Runnable() {
        @Override
        public void run() {
            // 在这里进行 http request.网络请求相关操作
            Message msg = new Message();
            Bundle data = new Bundle();
            File file = new File(fileUrl);
            Map<String,String> map = new HashMap();
            map.put("action","UpLoadStuPic");
            map.put("XHorKSH",xh);
            //判断身份
            if (identity.equals("新生"))
                map.put("type","0");
            else
                map.put("type","1");
            data.putString("value", UploadUtil.uploadFile(file, HttpConstant.hTTP_URl+"stuManagent.ashx?",map,"fileData"));
            msg.setData(data);
            handler.sendMessage(msg);
        }
    };

    /**
     * 选择图片
     */
    private void selectPicture(){
        /**
         *
         *  特此注意：由于Android 6.0 的权限是一套新的授权机制，所以在用法上也格外的不同。
         *  在此 MultiImageSelector（仿微信图片浏览）框架 会显示 “无权限”
         *  在此要对机型动态的获取文件读写权限
         *
         */
        String[] PERMISSIONS_STORAGE = {
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        };
        int permission = ActivityCompat.checkSelfPermission(SimpleCropActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(SimpleCropActivity.this, PERMISSIONS_STORAGE, Constant.REQUEST_EXTERNAL_STORAGE);
        }
        //调用 MultiImageSelector 图片预览功能
        MultiImageSelector.create(getApplication())
                .single() // 单选模式
                .start(SimpleCropActivity.this, Constant.REQUEST_IMAGE);
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant.REQUEST_IMAGE) {
            if (resultCode == RESULT_OK) {
                /***
                 *
                 * 1.显示裁剪控件，隐藏掉默认提示视图页面
                 * 2.循环将按钮变为可点击状态
                 * 3.保存按钮 动态显示
                 */
                cvSimple.setVisibility(View.VISIBLE);
                ivSave.setVisibility(View.VISIBLE);
                ivSimpleDefault.setVisibility(View.GONE);

                for (int i = 0; i < ibList.size(); i++) {
                    ibList.get(i).setClickable(true);
                }
                //获取当前图片路径 转成 URi的形式 放到图片裁剪器
                List<String> path = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                File file = new File(path.get(0));
                Uri fileUri = Uri.fromFile(file);
                cvSimple.startLoad(fileUri, new LoadCallback() {
                    @Override
                    public void onSuccess() {
                    }

                    @Override
                    public void onError() {
                    }
                });
            }
        }
    }


    /**
     * 显示加载dialog
     */
    public void initShowUserUpIconDialog(String content, Activity activity) {
        //加载进度
        userUpIconDialog = new MaterialDialog.Builder(activity)
                .content(content)
                .progress(true, 0)
                .show();
        // 设置点击屏幕Dialog不消失
        userUpIconDialog.setCanceledOnTouchOutside(false);
        //取消Back键监听
        userUpIconDialog.setCancelable(false);
    }

    @Override
    protected void onDestroy() {
        ButterKnife.unbind(this);
        EventBus.getDefault().unregister(this);
        finish();
        //销毁handler
        time_handler.removeCallbacks(time_runnable);
        initMyIconhandle.removeCallbacks(initMyIconRunnable);
        super.onDestroy();
    }
}
